package com.gexiaobao.pigeon.ui.fragment.mine.pigeon

import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import cn.qqtheme.framework.picker.OptionPicker
import cn.qqtheme.framework.widget.WheelView
import com.bumptech.glide.Glide
import com.facebook.drawee.backends.pipeline.Fresco
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.countDownCoroutines
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.DeviceListBean
import com.gexiaobao.pigeon.app.model.bean.FeatherColorResponse
import com.gexiaobao.pigeon.app.model.bean.PigeonBean
import com.gexiaobao.pigeon.app.model.param.RingInfoParams
import com.gexiaobao.pigeon.app.model.param.RingSnParams
import com.gexiaobao.pigeon.app.rxui.tablayout.listener.GlideEngine
import com.gexiaobao.pigeon.app.util.CacheUtil
import com.gexiaobao.pigeon.app.util.DatetimeUtil
import com.gexiaobao.pigeon.app.util.ImageLoaderManager
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.PictureUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.TransInformation
import com.gexiaobao.pigeon.databinding.FragmentAddPigeonBinding
import com.gexiaobao.pigeon.ui.dialog.BottomDeviceCodeDialog
import com.gexiaobao.pigeon.ui.dialog.DialogPigeonMasterName
import com.gexiaobao.pigeon.ui.dialog.PairCountDownDialog
import com.gexiaobao.pigeon.viewmodel.MyPigeonViewModel
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.loper7.date_time_picker.DateTimeConfig
import com.loper7.date_time_picker.dialog.CardDatePickerDialog
import com.luck.picture.lib.basic.PictureSelectionModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.language.LanguageConfig
import com.luck.picture.lib.style.PictureSelectorStyle
import com.yuyh.library.imgsel.ISNav
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import java.io.File

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 16:51
 * @Describe    : 添加赛鸽
 */
class FragmentAddPigeon : BaseFragment<MyPigeonViewModel, FragmentAddPigeonBinding>() {

    private lateinit var dialogTimer: PairCountDownDialog
    private val arrayList: ArrayList<DeviceListBean.DataList> = arrayListOf()
    private var mPosition = 0
    private var featherColorId = 0
    private var pigeonId = 0
    private var title: String = ""
    private var featherColor: String = ""
    private lateinit var mPigeonData: PigeonBean.RingInfo
    private var userName = ""
    private var mTypeIntent = 0
    private var mPigeonId: Int = 0
    private var pictureType = 0
    private var bodyPic: File? = null
    private var featherPic: File? = null
    private var leftHead: File? = null
    private var rightHeadPic: File? = null

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
        Fresco.initialize(context)
        ISNav.getInstance()
            .init { context, path, imageView -> Glide.with(context).load(path).into(imageView) }
        val userData = CacheUtil.getUser()
        if (userData != null) {
            userName = userData.realName
        }
        title = arguments?.getString("title")!!
        pigeonId = requireArguments().getInt("pigeonId")
        mTypeIntent = arguments?.getInt("type", 0)!!
        mDatabind.includeBar.toolbar.initClose(title) {
            nav().navigateUp()
        }
        val name = KvUtils.decodeString(Constant.MASTER_PIGEON_NAME)
        mViewModel.pigeonMasterName.set(name)
        mViewModel.pigeonSex.set("")
        mViewModel.pigeonEyePattern.set("")
        mDatabind.ivPicBody.scaleType = ImageView.ScaleType.FIT_XY
        mDatabind.ivPicWing.scaleType = ImageView.ScaleType.FIT_XY
        mDatabind.ivPicLeftHead.scaleType = ImageView.ScaleType.FIT_XY
        mDatabind.ivPicRightHead.scaleType = ImageView.ScaleType.FIT_XY

        showUIData(title)
        addTextWatch()
        checkedListeners()
        showDeviceList()
    }


    override fun initData() {
        super.initData()
        mDatabind.layoutRingNumber.tvRingNumber.transformationMethod = TransInformation()
        mDatabind.layoutFatherRingNumber.tvFatherRingNumber.transformationMethod = TransInformation()
        mDatabind.layoutMatherRingNumber.tvMatherRingNumber.transformationMethod = TransInformation()
    }

    private fun showDeviceList() {
        mViewModel.getDeviceList()
    }

    private fun showUIData(title: String) {
        when (title) {
            "赛鸽修改" -> {
                mPigeonData = arguments?.getSerializable("pigeonData") as PigeonBean.RingInfo
                mPigeonId = mPigeonData.pigeonId
                featherColor = arguments?.getString("featherColor")!!
                mViewModel.pigeonMasterName.set(mPigeonData.name)
                mViewModel.pigeonNickName.set("")
                featherColorId = mPigeonData.featherColor
                mViewModel.pigeonSex.set(mPigeonData.sex.toString())
                mViewModel.pigeonEyePattern.set(mPigeonData.eyePattern.toString())
                val ringId = mPigeonData.ringId.split("-")
                if (ringId.isNotEmpty() && ringId.size == 3) {
                    mDatabind.layoutRingNumber.tvRingNumberYear.setText(ringId[0])
                    mDatabind.layoutRingNumber.tvRingNumberArea.setText(ringId[1])
                    mDatabind.layoutRingNumber.tvRingNumber.setText(ringId[2])
                }

                mViewModel.pigeonRingSn.set(mPigeonData.ringSn)
                when (mPigeonData.sex) {
                    1 -> {
                        mDatabind.rbAddPigeonNo.isChecked = true
                    }

                    2 -> {
                        mDatabind.rbAddPigeonFemale.isChecked = true
                    }

                    3 -> {
                        mDatabind.rbAddPigeonMale.isChecked = true
                    }
                }
                mViewModel.pigeonFeatherColor.set(featherColor)
                when (mPigeonData.eyePattern) {
                    1 -> {
                        mDatabind.rbAddPigeonNoColor.isChecked = true
                    }

                    2 -> {
                        mDatabind.rbAddPigeonYellow.isChecked = true
                    }

                    3 -> {
                        mDatabind.rbAddPigeonSha.isChecked = true
                    }

                    4 -> {
                        mDatabind.rbAddPigeonNiu.isChecked = true
                    }
                }
                val fatherRingId = mPigeonData.fatherRingId.split("-")
                if (fatherRingId.isNotEmpty() && fatherRingId.size == 3) {
                    mDatabind.layoutFatherRingNumber.tvFatherRingNumberYear.setText(fatherRingId[0])
                    mDatabind.layoutFatherRingNumber.tvFatherRingNumberArea.setText(fatherRingId[1])
                    mDatabind.layoutFatherRingNumber.tvFatherRingNumber.setText(fatherRingId[2])
                }
                val motherRingId = mPigeonData.motherRingId.split("-")
                if (motherRingId.isNotEmpty() && motherRingId.size == 3) {
                    mDatabind.layoutMatherRingNumber.tvMatherRingNumberYear.setText(motherRingId[0])
                    mDatabind.layoutMatherRingNumber.tvMatherRingNumberArea.setText(motherRingId[1])
                    mDatabind.layoutMatherRingNumber.tvMatherRingNumber.setText(motherRingId[2])
                }
                mViewModel.pigeonRaiser.set(mPigeonData.raiser)

                mViewModel.pigeonBirthday.set(mPigeonData.birthday)
                mViewModel.pigeonDesc.set(mPigeonData.pigeonDesc)
                if (mPigeonData.bodyPicPath.isNotEmpty()) {
                    ImageLoaderManager.loadRoundImage(
                        context,
                        mPigeonData.bodyPicPath,
                        mDatabind.ivPicBody,
                        10
                    )
                }
                ImageLoaderManager.loadRoundImage(
                    context,
                    mPigeonData.featherPicPath,
                    mDatabind.ivPicWing,
                    10
                )
                ImageLoaderManager.loadRoundImage(
                    context,
                    mPigeonData.leftHeadPicPath,
                    mDatabind.ivPicLeftHead,
                    10
                )
                ImageLoaderManager.loadRoundImage(
                    context,
                    mPigeonData.rightHeadPicId,
                    mDatabind.ivPicRightHead,
                    10
                )
            }

            "添加赛鸽" -> {

            }
        }
    }

    private fun addTextWatch() {
        mDatabind.layoutRingNumber.tvRingNumberYear.addTextChangedListener {
            if (it?.length == 4) {
                mDatabind.layoutRingNumber.tvRingNumberArea.requestFocus()
            }
        }

        mDatabind.layoutRingNumber.tvRingNumberArea.addTextChangedListener {
            if (it?.length == 2) {
                mDatabind.layoutRingNumber.tvRingNumber.requestFocus()
            }
        }

        mDatabind.layoutFatherRingNumber.tvFatherRingNumberYear.addTextChangedListener {
            if (it?.length == 4) {
                mDatabind.layoutFatherRingNumber.tvFatherRingNumberArea.requestFocus()
            }
        }

        mDatabind.layoutFatherRingNumber.tvFatherRingNumberArea.addTextChangedListener {
            if (it?.length == 2) {
                mDatabind.layoutFatherRingNumber.tvFatherRingNumber.requestFocus()
            }
        }

        mDatabind.layoutMatherRingNumber.tvMatherRingNumberYear.addTextChangedListener {
            if (it?.length == 4) {
                mDatabind.layoutFatherRingNumber.tvFatherRingNumberArea.requestFocus()
            }
        }

        mDatabind.layoutFatherRingNumber.tvFatherRingNumberArea.addTextChangedListener {
            if (it?.length == 2) {
                mDatabind.layoutMatherRingNumber.tvMatherRingNumber.requestFocus()
            }
        }
    }

    private fun checkedListeners() {
        mDatabind.rbAddPigeonNo.setOnCheckedChangeListener { _, b ->
            if (b) mViewModel.pigeonSex.set("1")
        }

        mDatabind.rbAddPigeonMale.setOnCheckedChangeListener { _, b ->
            if (b) mViewModel.pigeonSex.set("3")

        }
        mDatabind.rbAddPigeonFemale.setOnCheckedChangeListener { _, b ->
            if (b) mViewModel.pigeonSex.set("2")
        }

        mDatabind.rbAddPigeonNoColor.setOnCheckedChangeListener { _, b ->
            if (b) mViewModel.pigeonEyePattern.set("1")
        }

        mDatabind.rbAddPigeonYellow.setOnCheckedChangeListener { _, b ->
            if (b) mViewModel.pigeonEyePattern.set("2")
        }

        mDatabind.rbAddPigeonSha.setOnCheckedChangeListener { _, b ->
            if (b) mViewModel.pigeonEyePattern.set("3")
        }

        mDatabind.rbAddPigeonNiu.setOnCheckedChangeListener { _, b ->
            if (b) mViewModel.pigeonEyePattern.set("4")
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.tvAddPigeonCommit,
            mDatabind.tvAddPigeonColor,
            mDatabind.ivAddPigeonColor,
            mDatabind.rlPicBody,
            mDatabind.rlPicWing,
            mDatabind.rlPicLeftHead,
            mDatabind.rlPicRightHead,
            mDatabind.tvPair,
            mDatabind.ivAddPigeonMaster,
            mDatabind.ivDeleteBodyPic,
            mDatabind.ivDeleteBodyWing,
            mDatabind.ivDeleteBodyLeftHead,
            mDatabind.ivDeleteBodyRightHead,
            mDatabind.tvPigeonBirthday
        ) {
            when (it) {
                mDatabind.tvAddPigeonCommit -> {
                    commitPigeonData()
                }

                mDatabind.tvAddPigeonColor, mDatabind.ivAddPigeonColor -> {
                    showLoading()
                    mViewModel.getFeatherColor()
                }

                mDatabind.rlPicBody -> {
                    pictureType = 1
                    selectBodyPic()
                }

                mDatabind.rlPicWing -> {
                    pictureType = 2
                    selectBodyPic()
                }

                mDatabind.rlPicLeftHead -> {
                    pictureType = 3
                    selectBodyPic()
                }

                mDatabind.rlPicRightHead -> {
                    pictureType = 4
                    selectBodyPic()
                }

                mDatabind.tvPair -> {
                    showCountDownDialog()
                }

                mDatabind.ivAddPigeonMaster -> {
                    showPigeonMasterName()
                }

                mDatabind.ivDeleteBodyPic -> {
                    mDatabind.ivPicBody.setImageBitmap(null)
                    bodyPic = null
                    mDatabind.ivDeleteBodyPic.visibility = View.GONE
                }

                mDatabind.ivDeleteBodyWing -> {
                    mDatabind.ivPicWing.setImageBitmap(null)
                    featherPic = null
                    mDatabind.ivDeleteBodyWing.visibility = View.GONE
                }

                mDatabind.ivDeleteBodyLeftHead -> {
                    mDatabind.ivPicLeftHead.setImageBitmap(null)
                    leftHead = null
                    mDatabind.ivDeleteBodyLeftHead.visibility = View.GONE
                }

                mDatabind.ivDeleteBodyRightHead -> {
                    mDatabind.ivPicRightHead.setImageBitmap(null)
                    rightHeadPic = null
                    mDatabind.ivDeleteBodyRightHead.visibility = View.GONE
                }

                mDatabind.tvPigeonBirthday -> {
                    chooseDate()
                }
            }
        }
    }

    private fun showCountDownDialog() {
        if (arrayList.isEmpty()) {
            showMessage(getString(R.string.No_device_is_bound))
            return
        }
        if (job != null) {
            job?.cancel()
        }
        toPairRingSn()
        dialogTimer = PairCountDownDialog(context)
        dialogTimer.setCanceledOnTouchOutside(false)
        dialogTimer.setFullScreenWidth()
        dialogTimer.show()
        //开启倒计时60s
        job = countDownCoroutines(20, {
            dialogTimer.setCountDownTime(it)
        }, {
            dialogTimer.dismiss()
            if (job != null) {
                job!!.cancel()
            }
        }, lifecycleScope)
    }

    private fun chooseDate() {
        val displayList: MutableList<Int> = mutableListOf()
        displayList.add(DateTimeConfig.YEAR)
        displayList.add(DateTimeConfig.MONTH)
        displayList.add(DateTimeConfig.DAY)
        val dialog = context?.let { it ->
            CardDatePickerDialog.builder(it)
                .setTitle(getString(R.string.option_date))
                .setDisplayType(displayList)
                .setBackGroundModel(CardDatePickerDialog.STACK)
                .showBackNow(false)//是否显示一键回到今日 和 定位到今天的日期
                .setPickerLayout(0)
                .setTouchHideable(true)
                .setChooseDateModel(DateTimeConfig.DATE_LUNAR)
                .setWrapSelectorWheel(false)
                .setThemeColor(Color.parseColor("#FF8000"))
                .showDateLabel(false)
                .showFocusDateInfo(false)
                .setOnChoose(getString(R.string.select)) {
                    mViewModel.pigeonBirthday.set(DatetimeUtil.conversionTime(it, "yyyy-MM-dd"))
                }
                .setOnCancel(getString(R.string.closed)) {
                }.build()
        }
        dialog?.show()
        //重点 需要在dialog show 方法后得到 BottomSheetDialog 实体，设置其 isHideable 为 fasle
        (dialog as BottomSheetDialog).behavior.isHideable = false
    }

    private fun showPigeonMasterName() {
        val dialog = DialogPigeonMasterName(context)
//        dialog.setName1(name)
        dialog.setName2(userName)
        dialog.setName1Listener {
            mViewModel.pigeonMasterName.set(dialog.getName1Text())
            dialog.dismiss()
        }
        dialog.setName2lListener {
            mViewModel.pigeonMasterName.set(dialog.getName2Text())
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    /** 配对获取电子环号 */
    private fun toPairRingSn() {
        var deviceCode = ""
        if (arrayList.size == 1) {
            deviceCode = arrayList[0].imsi
        } else {
            val bottomDialog = BottomDeviceCodeDialog(arrayList, getString(R.string.select_device))
            bottomDialog.setOnItemClickListener(object : BottomDeviceCodeDialog.OnItemClickCode {
                override fun setOnItemClickListener(content: String) {
                    bottomDialog.dismiss()
                    val body = RingSnParams(content)
                    mViewModel.geyRingSn(body)
                }
            })
            activity?.let { bottomDialog.show(it.supportFragmentManager, "deviceCode") }
        }
        val body = RingSnParams(deviceCode)
        mViewModel.geyRingSn(body)
    }

    private fun selectBodyPic() {
        val selectionModel: PictureSelectionModel = PictureSelector.create(context)
            .openGallery(SelectMimeType.ofImage())
            .setSelectorUIStyle(PictureSelectorStyle())
            .setImageEngine(GlideEngine.createGlideEngine())
            .setSelectionMode(SelectModeConfig.SINGLE)
            .setCompressEngine(PictureUtil.getCompressFileEngine())
//            .setCameraInterceptListener(PictureUtil.getCustomCameraEvent())
            .setPermissionDescriptionListener(PictureUtil.getPermissionDescriptionListener())
            .setPreviewInterceptListener(PictureUtil.getPreviewInterceptListener())
            .setPermissionDeniedListener(PictureUtil.getPermissionDeniedListener())
            .isLoopAutoVideoPlay(false)
            .isPageSyncAlbumCount(true)
            .setLanguage(LanguageConfig.SYSTEM_LANGUAGE)
            .setQuerySortOrder("")
            .isDisplayCamera(true)
            .isOpenClickSound(true)
            .isPreviewImage(false)
            .isMaxSelectEnabledMask(false)
            .isDirectReturnSingle(false)
            .setMaxSelectNum(1)
        selectionModel.forResult(object : OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: ArrayList<LocalMedia>?) {
                val imageFile = File(result!![0].realPath)
                when (pictureType) {
                    1 -> {
                        mDatabind.ivDeleteBodyPic.visibility = View.VISIBLE
                        bodyPic = imageFile
                        mDatabind.ivPicBody.setImageURI(Uri.parse("file://" + result[0].realPath))
                    }

                    2 -> {
                        mDatabind.ivDeleteBodyWing.visibility = View.VISIBLE
                        featherPic = imageFile
                        mDatabind.ivPicWing.setImageURI(Uri.parse("file://" + result[0].realPath))
                    }

                    3 -> {
                        mDatabind.ivDeleteBodyLeftHead.visibility = View.VISIBLE
                        leftHead = imageFile
                        mDatabind.ivPicLeftHead.setImageURI(Uri.parse("file://" + result[0].realPath))
                    }

                    4 -> {
                        mDatabind.ivDeleteBodyRightHead.visibility = View.VISIBLE
                        rightHeadPic = imageFile
                        mDatabind.ivPicRightHead.setImageURI(Uri.parse("file://" + result[0].realPath))
                    }
                }
            }

            override fun onCancel() {}
        })
    }

    private fun commitPigeonData() {
        when {
            mViewModel.pigeonMasterName.get().isEmpty() -> showMessage(getString(R.string.please_select_foster))
            mDatabind.layoutRingNumber.tvRingNumberYear.text!!.isEmpty() || mDatabind.layoutRingNumber.tvRingNumberYear.text!!.length != 4 -> showMessage(
                getString(R.string.ring_year_fail)
            )

            mDatabind.layoutRingNumber.tvRingNumberArea.text!!.isEmpty() || mDatabind.layoutRingNumber.tvRingNumberArea.text!!.length != 2 -> showMessage(
                getString(R.string.ring_area_fail)
            )

            mDatabind.layoutRingNumber.tvRingNumber.text!!.isEmpty() -> showMessage(getString(R.string.please_enter_success_ring))
            mViewModel.pigeonRingSn.get().isEmpty() -> showMessage(getString(R.string.no_pair_sn))
            mViewModel.pigeonSex.get().isEmpty() -> showMessage(getString(R.string.no_select_pigeon_sex))
            mViewModel.pigeonFeatherColor.get().isEmpty() -> showMessage(getString(R.string.hint_choose_feather_color))
            mViewModel.pigeonEyePattern.get().isEmpty() -> showMessage(getString(R.string.hint_choose_eye))
            else -> {
                val pigeonRingId =
                    mDatabind.layoutRingNumber.tvRingNumberYear.text.toString() + "-" + mDatabind.layoutRingNumber.tvRingNumberArea.text + "-" + mDatabind.layoutRingNumber.tvRingNumber.text

                val fatherRingId =
                    if (mDatabind.layoutFatherRingNumber.tvFatherRingNumberYear.text!!.isEmpty() && mDatabind.layoutFatherRingNumber.tvFatherRingNumberArea.text!!.isEmpty() && mDatabind.layoutFatherRingNumber.tvFatherRingNumber.text!!.isEmpty()) {
                        ""
                    } else {
                        mDatabind.layoutFatherRingNumber.tvFatherRingNumberYear.text.toString() + "-" + mDatabind.layoutFatherRingNumber.tvFatherRingNumberArea.text + "-" + mDatabind.layoutFatherRingNumber.tvFatherRingNumber.text
                    }
                val motherRingId =
                    if (mDatabind.layoutMatherRingNumber.tvMatherRingNumberYear.text!!.isEmpty() && mDatabind.layoutFatherRingNumber.tvFatherRingNumberArea.text!!.isEmpty() && mDatabind.layoutMatherRingNumber.tvMatherRingNumber.text!!.isEmpty()) {
                        ""
                    } else {
                        mDatabind.layoutMatherRingNumber.tvMatherRingNumberYear.text.toString() + "-" + mDatabind.layoutFatherRingNumber.tvFatherRingNumberArea.text + "-" + mDatabind.layoutMatherRingNumber.tvMatherRingNumber.text
                    }
                val birthday = mViewModel.pigeonBirthday.get()
//                    if (tv_pigeon_birthday_year.text!!.isEmpty() && tv_pigeon_birthday_month.text!!.isEmpty() && tv_pigeon_birthday_day.text!!.isEmpty()) {
//                        ""
//                    } else {
//                        tv_pigeon_birthday_year.text.toString() + "-" + tv_pigeon_birthday_month.text + "-" + tv_pigeon_birthday_day.text
//                    }
                showLoading()
                if (mTypeIntent == 1) {
                    val bean = RingInfoParams(
                        fosterName = mViewModel.pigeonMasterName.get().trim(),
                        pigeonName = mViewModel.pigeonNickName.get().trim(),
                        ringId = pigeonRingId.toUpperCase(),
                        ringSn = mViewModel.pigeonRingSn.get(),
                        sex = mViewModel.pigeonSex.get().toInt(),
                        featherColor = featherColorId,
                        eyePattern = mViewModel.pigeonEyePattern.get().toInt(),
                        bodyPic = bodyPic,
                        featherPic = featherPic,
                        leftHead = leftHead,
                        rightHeadPic = rightHeadPic,
                        fatherRingId = fatherRingId.toUpperCase(),
                        motherRingId = motherRingId.toUpperCase(),
                        birthday = birthday,
                        raiser = mViewModel.pigeonRaiser.get().trim(),
                        pigeonDesc = mViewModel.pigeonDesc.get().trim()
                    )
                    mViewModel.createPigeon(bean)
                } else {
                    val bean = RingInfoParams(
                        id = mPigeonId,
                        fosterName = mViewModel.pigeonMasterName.get().trim(),
                        pigeonName = mViewModel.pigeonNickName.get().trim(),
                        ringId = pigeonRingId.toUpperCase(),
                        ringSn = mViewModel.pigeonRingSn.get(),
                        sex = mViewModel.pigeonSex.get().toInt(),
                        featherColor = featherColorId,
                        eyePattern = mViewModel.pigeonEyePattern.get().toInt(),
                        bodyPic = bodyPic,
                        featherPic = featherPic,
                        leftHead = leftHead,
                        rightHeadPic = rightHeadPic,
                        fatherRingId = fatherRingId.toUpperCase(),
                        motherRingId = motherRingId.toUpperCase(),
                        birthday = birthday,
                        raiser = mViewModel.pigeonRaiser.get().trim(),
                        pigeonDesc = mViewModel.pigeonDesc.get().trim()
                    )
                    mViewModel.upDatePigeon(bean)
                }
            }
        }
    }


    override fun createObserver() {
        super.createObserver()
        mViewModel.featherColor.observe(this) {
            if (it.isSuccess) {
                pigeonFeatherColor(it.listData)
            } else {
                RxToast.showToast(it.errMessage)
            }
        }

        mViewModel.deviceList.observe(this) {
            if (!it.isEmpty()) {
                arrayList.clear()
                arrayList.addAll(it.list)
            }
        }

        mViewModel.ringSn.observe(this) { result ->
            dialogTimer.dismiss()
            job?.cancel()
            parseState(result, {
//                dismissLoading()
                mViewModel.pigeonRingSn.set(it.ringSn)
            }, {
                RxToast.showToast(it.msg)
            })
        }

        mViewModel.createPigeon.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                KvUtils.encode(Constant.MASTER_PIGEON_NAME, mViewModel.pigeonMasterName.get())
                if (mTypeIntent == 1) {
                    nav().navigateUp()
                } else {
                    nav().navigateUp()
                    eventViewModel.toModifyPigeonResult.value = pigeonId
//                    nav().popBackStack(R.id.fragment_detail_pigeon, true)
                }
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        mViewModel.modifyPigeonPicResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                nav().navigateUp()
                eventViewModel.toModifyPigeonResult.value = pigeonId
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
    }

    private fun pigeonFeatherColor(listData: ArrayList<FeatherColorResponse.ColorList>?) {
        val flyKey: ArrayList<String> = arrayListOf()
        if (listData != null && listData.size != 0) {
            for (item in listData) {
                flyKey.add(item.featherColor)
            }
            for ((index, item) in listData.withIndex()) {
                if (item.featherColor == featherColor) {
                    mPosition = index
                    break
                } else {
                    mPosition = 2
                }
            }
        }

        val picker = OptionPicker(activity, flyKey)
        val params = picker.window.attributes
        params.width = activity?.windowManager?.defaultDisplay!!.width
        picker.setCanceledOnTouchOutside(false)
        picker.setDividerRatio(WheelView.DividerConfig.FILL)
        picker.setShadowColor(resources.getColor(R.color.bg_light_bllue), 40)
        picker.selectedIndex = mPosition
        picker.setCycleDisable(true)
        picker.setTitleText(getString(R.string.hint_choose_feather_color))
        picker.setTitleTextColor(Color.BLACK)
        picker.setTitleTextSize(18)
        picker.setSubmitText(getString(R.string.sure))
        picker.setSubmitTextSize(17)
        picker.setSubmitTextColor(resources.getColor(R.color.bg_light_bllue))//确定按钮文字颜色
        picker.setCancelText(getString(R.string.cancel))
        picker.setCancelTextSize(17)
        picker.setCancelTextColor(resources.getColor(R.color.bg_light_bllue))//取消按钮文字颜色
        picker.setTextSize(18)
        picker.setLineSpaceMultiplier(3.0F)
        picker.setOnOptionPickListener(object : OptionPicker.OnOptionPickListener() {
            override fun onOptionPicked(index: Int, item: String) {
                mViewModel.pigeonFeatherColor.set(item)
                mViewModel.pigeonFeatherColorPosition.set(index + 1)
                mPosition = index
                featherColorId = listData?.get(index)!!.id
            }
        })
        picker.show()
    }
}